#include "PicWidget.h"
#include <QPainter>
#include <QApplication>

PicWidget::PicWidget(QWidget *parent) : QLabel(parent)
{
    setStyleSheet("background-color: white;");
    setScaledContents(true);  // 启用缩放
}

void PicWidget::setPixmap(const QPixmap& pixmap)
{
    m_pixmap = pixmap;
    update();
}

QPixmap PicWidget::getPixmap()
{
    return m_pixmap;
}

void PicWidget::UpdateTextInfo(const TextInfos& info)
{
    m_Textinfos.insert(info.index, info);
    update();
}

void PicWidget::UpdateText(const QList<QVariant> &info)
{
    int i = 0;
    QMapIterator<int, TextInfos> it(m_Textinfos);
    while (it.hasNext()) {
        it.next();
        TextInfos Textinfo = it.value();
        Textinfo.m_text = info.at(i).toString();
        m_Textinfos.insert(it.key(), Textinfo);
        i++;
    }
    update();
}

void PicWidget::removeTextInfo(int index)
{
    m_Textinfos.remove(index);
    update();
}

void PicWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);  // 启用抗锯齿
    painter.setRenderHint(QPainter::TextAntialiasing, true);  // 启用文本抗锯齿
    if(!m_pixmap.isNull())
    {
        int originalWidth = m_pixmap.width();
        int originalheight = m_pixmap.height();

        int widgetWidth = parentWidget()->width();
        int widgetHeight = parentWidget()->height();

        qreal scaleX = static_cast<qreal>(widgetWidth) / originalWidth;
        qreal scaleY = static_cast<qreal>(widgetHeight) / originalheight;

        qreal scale = qMin(scaleX,scaleY);

        int newWidth = static_cast<int>(originalWidth*scale);
        int newHeight = static_cast<int>(originalheight*scale);
        int x = (widgetWidth-newWidth)/2;
        int y = (widgetHeight-newHeight)/2;
        this->setGeometry(x,y,newWidth,newHeight);

        painter.drawPixmap(0, 0, newWidth, newHeight, m_pixmap);
    }
    QMapIterator<int, TextInfos> it(m_Textinfos);
    while (it.hasNext()) {
        it.next();
        painter.setFont(it.value().m_Font);
        // 文本内容
        QString text = it.value().m_text;
        // 设置起始位置
        int x = it.value().m_Point.x();
        int y = it.value().m_Point.y();

        for (int i = 0; i < text.length(); ++i) {
            painter.drawText(x, y, QString(text[i]));
            if(it.value().m_direction == 0)
            {
                x += it.value().m_interval;  // 每个字符之间的垂直间距
            }
            else if(it.value().m_direction == 1)
            {
                y += it.value().m_interval;  // 每个字符之间的垂直间距
            }
        }
    }
}
